from PIL import Image
import yaml


def save_cutedImgs(item_row, item_col, item_width, item_height, savePath, fileName, qualityPar):
    # 设置允许读入的文件最大值
    Image.MAX_IMAGE_PIXELS = 930000000
    # 打开原图像
    image = Image.open(filePath)
    print('正在切割图片......')
    for x in list(range(item_row)):
        for y in list(range(item_col)):
            startW = item_width * y
            endW = item_width * (y + 1)
            startH = x * item_height
            endH = item_height * (x + 1)
            # 区域LTRB
            box = (startW, startH, endW, endH)
            region = image.crop(box)
            region.save(savePath + fileName + '_%s_%s.jpg' % (x, y), quality=qualityPar)



def calc_image(filePath, item_width, item_height):
    # 设置允许读入的文件最大值
    Image.MAX_IMAGE_PIXELS = 930000000
    # 打开原图像
    image = Image.open(filePath)
    # 原图像的宽高
    width, height = image.size
    # 切割后矩阵内横向/纵向个数
    item_col = int(width / item_width)
    item_row = int(height / item_height)
    # 计算切片的横向和纵向数量
    # 计算编码，编码从0开始，小于(数量-1)
    if width % item_width == 0:
        item_col = int(width / item_width)
    else:
        item_col = int(width // item_width + 1)
    if height % item_height == 0:
        item_row = int(height / item_height)
    else:
        item_row = int(height // item_height + 1)

    calcDict = {'item_row': item_row, 'item_col': item_col}
    print('计算编码完毕')
    # 返回标识——编码：行/列，像素大小X*Y
    return calcDict


if __name__ == '__main__':
    # 读取配置文件信息
    configData = open('./config.yml', 'rb')
    data = yaml.load(configData)
    # 获取配置文件信息
    filePath = data['filePath']
    savePath = data['savePath']
    pixelSize = data['pixelSize']
    varyCut = data['varyCut']
    fileName = str(data['fileName'])
    item_width = pixelSize
    item_height = pixelSize
    # 计算图片编码
    calcData = calc_image(filePath, item_width, item_height)
    # 切割并保存图片
    if varyCut == 0:
        save_cutedImgs(calcData['item_row'], calcData['item_col'], item_width, item_height, savePath, fileName+'big', 95)
        print('执行完毕')
    else:
        save_cutedImgs(calcData['item_row'], calcData['item_col'], item_width, item_height, savePath, fileName+'big',
                       95)
        print('第一级切割完毕')
        save_cutedImgs(calcData['item_row'], calcData['item_col'], item_width, item_height, savePath, fileName+'middle',
                       15)
        print('第二级切割完毕')
        save_cutedImgs(calcData['item_row'], calcData['item_col'], item_width, item_height, savePath, fileName+'small',
                       5)
        print('第三级切割完毕')
        print('执行完毕')
